package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.redis.RedisServiceUtil;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsSystem;
import com.qiguliuxing.dts.service.base.DtsSystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/param")
@Validated
@Api(tags= ApiAdminConsts.Params.PARENT)
public class AdminParamsController {
    private static final Logger logger = LoggerFactory.getLogger(AdminParamsController.class);

    @Autowired
    private DtsSystemConfigService dtsSystemConfigService;

    @GetMapping("/list")
    @RequiresPermissions("admin:param:list")
    @RequiresPermissionsDesc(menu = { "系统管理", "系统参数" }, button = "查询")
    @ApiOperation(value = ApiAdminConsts.Params.LIST)
    @WebLog(description = ApiAdminConsts.Params.LIST, excludes = {LogParamsConsts.RESPONSE})
    public Object list(@ApiParam(value = "对象key") String key,
                       @ApiParam(value = "关键字") String keyWord,
                       @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
                       @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
                       @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
        List<DtsSystem> systemList = dtsSystemConfigService.querySelective(key, keyWord, page, limit, sort, order);
        long total = PageInfo.of(systemList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", systemList);

        return ResponseUtils.ok(data);
    }

    @PostMapping("/create")
    @RequiresPermissions("admin:param:create")
    @RequiresPermissionsDesc(menu = { "系统管理", "系统参数" }, button = "新增")
    @ApiOperation(value = ApiAdminConsts.Params.CREATE)
    @WebLog(description = ApiAdminConsts.Params.CREATE, persistence = true)
    public Object create(@RequestBody DtsSystem dtsSystem) {
        Object error = validate(dtsSystem);
        if (error != null) {
            return error;
        }
        dtsSystemConfigService.add(dtsSystem);
        //新增参数后需将新增的参数添加至redis缓存
        logger.info("新增参数key: {} ，参数值: {} 到 redis缓存", dtsSystem.getKeyName(), dtsSystem.getKeyValue());
        RedisServiceUtil.set(dtsSystem.getKeyName(), dtsSystem.getKeyValue());
        return ResponseUtils.ok(dtsSystem);
    }

    private Object validate(DtsSystem dtsSystem) {
        String keyName = dtsSystem.getKeyName();
        if (StringUtils.isEmpty(keyName)) {
            return ResponseUtils.badArgument();
        }
        String keyValue = dtsSystem.getKeyValue();
        if (StringUtils.isEmpty(keyValue)) {
            return ResponseUtils.badArgument();
        }
        String desc = dtsSystem.getDesc();
        if (StringUtils.isEmpty(desc)) {
            return ResponseUtils.badArgument();
        }
        return null;
    }

    @PostMapping("/update")
    @RequiresPermissions("admin:param:update")
    @RequiresPermissionsDesc(menu = { "系统管理", "系统参数" }, button = "编辑")
    @ApiOperation(value = ApiAdminConsts.Params.UPDATE)
    @WebLog(description = ApiAdminConsts.Params.UPDATE, persistence = true)
    public Object update(@RequestBody DtsSystem dtsSystem) {
        Object error = validate(dtsSystem);
        if (error != null) {
            return error;
        }
        if (dtsSystemConfigService.update(dtsSystem) == 0) {
            logger.error("系统管理->系统参数->编辑 错误:{}", "更新数据失败!");
            return ResponseUtils.updatedDataFailed();
        }
        logger.info("修改参数key: {} ，参数值: {} 到 redis缓存", dtsSystem.getKeyName(), dtsSystem.getKeyValue());
        RedisServiceUtil.set(dtsSystem.getKeyName(), dtsSystem.getKeyValue());

        return ResponseUtils.ok(dtsSystem);
    }

    @PostMapping("/delete")
    @RequiresPermissions("admin:param:delete")
    @RequiresPermissionsDesc(menu = { "系统管理", "系统参数" }, button = "删除")
    @ApiOperation(value = ApiAdminConsts.Params.DELETE)
    @WebLog(description = ApiAdminConsts.Params.DELETE, persistence = true)
    public Object delete(@RequestBody DtsSystem dtsSystem) {
        String keyName = dtsSystem.getKeyName();
        if (StringUtils.isEmpty(keyName)) {
            return ResponseUtils.badArgument();
        }
        Integer id = dtsSystem.getId();
        dtsSystemConfigService.deleteById(id);

        RedisServiceUtil.del(keyName);
        logger.info("已删除 redis缓存，参数key: {} ，参数值: {} ", dtsSystem.getKeyName(), dtsSystem.getKeyValue());

        return ResponseUtils.ok();
    }

}
